package api.tools;

import org.apache.commons.compress.utils.IOUtils;

import java.io.*;

public class FileTool {

	/**
	 * 默认根据UTF-8编码
	 * @param FileName
	 * @return
	 */
	public static String ReadFileToString(String FileName) {
		return ReadFileToString(FileName,"UTF-8");
	}
	public static String ReadFileToString(String FileName,String encoding) {
		try {
			FileInputStream FS = new FileInputStream(FileName);
			int size = FS.available();

			byte[] pp = new byte[size];

			FS.read(pp, 0, size);

			String ss = new String(pp,encoding);

			FS.close();

			return ss;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static boolean WriteStringToFile(String DataToWrite, String FileName,String encoding) {
        try {
            FileOutputStream FS = new FileOutputStream(FileName);
            
            byte[] pp = null;
            if(encoding != null){
                pp = DataToWrite.getBytes(encoding);
            }else{
                pp = DataToWrite.getBytes();
            }

            FS.write(pp);

            FS.close();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

	public static boolean WriteStringToFile(String DataToWrite, String FileName) {
	    return WriteStringToFile(DataToWrite,FileName,null);
	}


	public static boolean isDirExist(String dir) {
		File FF = new File(dir);
		if (FF.exists()) {
			if (FF.isDirectory()) {
				return true;
			}
		}
		return false;
	}
	
	public static void createFolder(String folderPath) {
        try {
            File myFilePath = new File(folderPath);
            if (!myFilePath.exists()) {
                myFilePath.mkdirs();
            }
        }
        catch (Exception e) {
            System.err.println("创建目录操作出错");
        }
    }

	/**
	 * 将内容流保存到指定的文件路径
	 *
	 * @param is
	 *            InputStream型，欲保存的内容
	 * @param destFile
	 *            File型，要保存到的文件名称
	 * @return 保存成功返回true，否则返回false
	 */
	public static boolean saveTo(InputStream is, File destFile) throws IOException {
		if (is == null)
			return false;
		File f = new File(destFile.getParent());
		if (!f.exists())
			f.mkdirs();
		FileOutputStream fos = new FileOutputStream(destFile);
		try {
			IOUtils.copy(is, fos);
		} finally {
			fos.close();
		}
		return true;
	}

	/**
	 * 将内容流保存到指定的文件路径
	 *
	 * @param is
	 *            InputStream型，欲保存的内容
	 * @param filename
	 *            String型，要保存到的文件名称
	 * @return 保存成功返回true，否则返回false
	 */
	public static boolean saveTo(InputStream is, String filename) throws IOException {
		File f = new File(filename);
		return saveTo(is, f);
	}
}

